<?php
// +----------------------------------------------------------------------
// | FastXCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.fastxcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;

// 模块参数后台程序安装
global $configinfo;
$configinfo['adminmodule'] = 1;

class AdminArticleController extends AdminBaseController
{
    /**
     * 文章列表
     * @adminMenu(
     *     'name'   => '文章管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
		global $configinfo;
		
        $content = hook_one('portal_admin_article_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();

        $categoryId = $this->request->param('category', 0, 'intval');
		
		// 【模块参数程序安装】文章列表搜索条件引入文件
		$configmodule="article";$configname="list";$setblock="where";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');

        $postService = new PostService();
        $data        = $postService->adminArticleList($param,$wherepara,$otherconfig);

        $data->appends($param);
		$articles=$data->items();

        $portalCategoryModel = new PortalCategoryModel();
        $categoryTree        = $portalCategoryModel->adminCategoryTree($categoryId,0,$configinfo['moduleid']);

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('articles', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('page', $data->render());
		
		// 【模块参数程序安装】文章列表引入文件
		$configmodule="article";$configname="list";$setblock="main";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');

		if($GLOBALS['_MGPC_REQ']['category'] == 9)
		{
       		return $this->fetch("../../../plugins/modulepara/config/hook/hook_configmodulepara/tpl/system_expcolumnlist");
		}else{
			return $this->fetch();
		}
    }

    /**
     * 添加文章
     * @adminMenu(
     *     'name'   => '添加文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章',
     *     'param'  => ''
     * )
     */
    public function add()
    {
		global $configinfo;
		
        $content = hook_one('portal_admin_article_add_view');

        if (!empty($content)) {
            return $content;
        }

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
		
        $portalCategoryModel = new PortalCategoryModel();
        $categoriesTree      = $portalCategoryModel->adminCategoryTree($configinfo['columninfo']['id'],0,$configinfo['moduleid']);
		$this->assign('categories_tree', $categoriesTree);
		
		// 【模块参数程序安装】文章详情添加页面引入文件
		$configmodule="article";$configname="detail";$setblock="add";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');
		
        return $this->fetch();
    }

    /**
     * 添加文章提交
     * @adminMenu(
     *     'name'   => '添加文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
		global $configinfo;
		
        if ($this->request->isPost()) {
            $data = $this->request->param();
			
			//状态只能设置默认值。未发布、未置顶、未推荐
            $data['post']['post_status'] = $data['post']['post_status'] ? $data['post']['post_status'] : 0;
            $data['post']['is_top']      = $data['post']['is_top'] ? $data['post']['is_top'] : 0;
            $data['post']['recommended'] = $data['post']['recommended'] ? $data['post']['recommended'] : 0;	
			
			$post = $data['post'];

            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }

            $portalPostModel = new PortalPostModel();
			// 新增自定义模块独立表配置 DATE:2020-3-27 START
			$moduletable = getmoduletable($configinfo['moduleid']);
			$moduletable = delthstr($moduletable,"fastxcms_","");
			$portalPostModel->name($moduletable);
			// 新增自定义模块独立表配置 DATE:2020-3-27 END

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);

            $data['post']['id'] = $portalPostModel->id;
            $hookParam          = [
                'is_add'  => true,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);
			
			// 【模块参数程序安装】文章详情插件数据库引入文件
			$configmodule="article";$configname="detail";$setblock="insert";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');
			
			if($downlangurl)
			{
            	$this->success('添加成功!继续添加下一个语言!', $downlangurl);
			}else{
				$this->success('添加成功!', "/portal/admin_article/edit/id/".$portalPostModel->id.".html".$configinfo['moreurl']);	
			}
        }

    }

    /**
     * 编辑文章
     * @adminMenu(
     *     'name'   => '编辑文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
		global $configinfo;
		
        $content = hook_one('portal_admin_article_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');

        $portalPostModel = new PortalPostModel();
		// 新增自定义模块独立表配置 DATE:2020-3-27 START
		$moduletable = getmoduletable($configinfo['moduleid']);
		$moduletable = delthstr($moduletable,"fastxcms_","");
		$portalPostModel->name($moduletable);
		// 新增自定义模块独立表配置 DATE:2020-3-27 END
		
		// 【模块参数程序安装】文章详情修改页面引入文件
		$configmodule="article";$configname="detail";$setblock="supplierconfig";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');
		
        $post            = $portalPostModel->where('id', $id)->find();
		$postCategories = "";
		$postCategoryIds = "";
		if($post['categories'])
		{
			$portalCategoryModel = new PortalCategoryModel();
			$categorywhere = "id in(".$post['categories'].")";
			$categories = $portalCategoryModel->where($categorywhere)->select()->toArray();
			foreach($categories as $key=>$val)
			{
				$postCategories[$val['id']]  = $val['name'];
			}
			$postCategoryIds = implode(',', array_keys($postCategories));
		}

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        $this->assign('post', $post);
		$this->assign('post_categories', $postCategories);
		$this->assign('post_category_ids', $postCategoryIds);
		
        $portalCategoryModel = new PortalCategoryModel();
        $categoriesTree      = $portalCategoryModel->adminCategoryTree($post['category_id'],0,$configinfo['moduleid']);
		$this->assign('categories_tree', $categoriesTree);
		
		// 【模块参数程序安装】文章详情修改页面引入文件
		$configmodule="article";$configname="detail";$setblock="edit";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');

        return $this->fetch();
    }

    /**
     * 编辑文章提交
     * @adminMenu(
     *     'name'   => '编辑文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
		global $configinfo,$_MGPC_GET;
		
        if ($this->request->isPost()) {
            $data = $this->request->param();

            //需要抹除发布、置顶、推荐的修改。
            //unset($data['post']['post_status']);
            //unset($data['post']['is_top']);
            //unset($data['post']['recommended']);

            $post   = $data['post'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }

            $portalPostModel = new PortalPostModel();
			// 新增自定义模块独立表配置 DATE:2020-3-27 START
			$moduletable = getmoduletable($configinfo['moduleid']);
			$moduletable = delthstr($moduletable,"fastxcms_","");
			$portalPostModel->name($moduletable);
			// 新增自定义模块独立表配置 DATE:2020-3-27 END

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $portalPostModel->adminEditArticle($data['post'], $data['post']['categories']);

            $hookParam = [
                'is_add'  => false,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);
			
			// 【模块参数程序安装】文章详情修改数据库引入文件
			$configmodule="article";$configname="detail";$setblock="update";include(MODULEPARA_PATH.'/configmodule/configmodulepara/configmodule.php');

			if(empty($_MGPC_GET['listattrid']) && empty($configinfo['morepara']['supplierconfig']))
			{
            	$this->success('保存成功!', "/portal/admin_article/index.html".$configinfo['moreurl']);
			}else{
				$this->success('保存成功!');	
			}

        }
    }

    /**
     * 文章删除
     * @adminMenu(
     *     'name'   => '文章删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
		global $configinfo,$supplier_id;
		
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
		// 新增自定义模块独立表配置 DATE:2020-3-27 START
		$moduletable = getmoduletable($configinfo['moduleid']);
		$moduletable = delthstr($moduletable,"fastxcms_","");
		$portalPostModel->name($moduletable);
		// 新增自定义模块独立表配置 DATE:2020-3-27 END

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');
            $result       = $portalPostModel->where(['id' => $id])->find();
            $data         = [
                'object_id'   => $result['id'],
                'create_time' => time(),
                'table_name'  => $moduletable,
				'moduleid'  => $configinfo['moduleid'],
				'supplier_id'  => $supplier_id,
                'name'        => $result['post_title'],
				'user_id'     => cmf_get_current_admin_id()
            ];
            $resultPortal = $portalPostModel
                ->where(['id' => $id])
                ->update(['delete_time' => time()]);
            if ($resultPortal) {
                Db::name('recycleBin')->insert($data);
            }
            $this->success("删除成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);

        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $portalPostModel->where(['id' => ['in', $ids]])->select();
            $result  = $portalPostModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
            if ($result) {
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['id'],
                        'create_time' => time(),
                        'table_name'  => $moduletable,
						'moduleid'  => $configinfo['moduleid'],
						'supplier_id'  => $supplier_id,
                        'name'        => $value['post_title'],
						'user_id'     => cmf_get_current_admin_id()
                    ];
                    Db::name('recycleBin')->insert($data);
                }
                $this->success("删除成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);
            }
        }
    }

    /**
     * 文章发布
     * @adminMenu(
     *     'name'   => '文章发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章发布',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
		global $configinfo;
		
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
		// 新增自定义模块独立表配置 DATE:2020-3-27 START
		$moduletable = getmoduletable($configinfo['moduleid']);
		$moduletable = delthstr($moduletable,"fastxcms_","");
		$portalPostModel->name($moduletable);
		// 新增自定义模块独立表配置 DATE:2020-3-27 END

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

            $this->success("设置成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);
        }

        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

            $this->success("取消设置成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);
        }

    }

    /**
     * 文章置顶
     * @adminMenu(
     *     'name'   => '文章置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
		global $configinfo;
		
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
		// 新增自定义模块独立表配置 DATE:2020-3-27 START
		$moduletable = getmoduletable($configinfo['moduleid']);
		$moduletable = delthstr($moduletable,"fastxcms_","");
		$portalPostModel->name($moduletable);
		// 新增自定义模块独立表配置 DATE:2020-3-27 END

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 1]);

            $this->success("置顶成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 0]);

            $this->success("取消置顶成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);
        }
    }

    /**
     * 文章推荐
     * @adminMenu(
     *     'name'   => '文章推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
		global $configinfo;
		
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();
		// 新增自定义模块独立表配置 DATE:2020-3-27 START
		$moduletable = getmoduletable($configinfo['moduleid']);
		$moduletable = delthstr($moduletable,"fastxcms_","");
		$portalPostModel->name($moduletable);
		// 新增自定义模块独立表配置 DATE:2020-3-27 END

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 1]);

            $this->success("推荐成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);

        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 0]);

            $this->success("取消推荐成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);

        }
    }

    /**
     * 文章排序
     * @adminMenu(
     *     'name'   => '文章排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
		global $configinfo;
		
        parent::listOrders(Db::name('portal_post'));
        $this->success("排序更新成功！", "/portal/admin_article/index.html".$configinfo['moreurl']);
    }

    public function move()
    {

    }

    public function copy()
    {

    }


}
